<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>管理员站点列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索 -->
    <el-form :inline="true" style="margin-top: 20px;">
      <el-form-item>
        <el-button size="small" @click="exportExcel">导出Excel</el-button>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="name"
          placeholder="请输入充电桩名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="detail"
          placeholder="请输入详细地址"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="status" placeholder="请选择站点状态">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="phone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item>
                <el-select size="small" v-model="userType" placeholder="请选择是否平台合伙人">
                    <el-option v-for="item in options1" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item> -->
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="chongzhi"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="upAdminSite()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table
      size="small"
      ref="multipleTable"
      :data="siteData"
      element-loading-text="拼命加载中"
      style="width: 100%;"
      v-horizontal-scroll
    >
      <el-table-column
        align="center"
        sortable
        type="index"
        label="序号"
      ></el-table-column>
      <!-- <el-table-column align="center" sortable prop="id" label="站点Id" width="120"></el-table-column> -->
      <el-table-column
        align="center"
        sortable
        prop="name"
        label="站点名称"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="latitude"
        label="纬度"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="longitude"
        label="经度"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="status"
        label="站点状态"
        :formatter="Status"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="parkCost"
        label="停车费"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="detail"
        label="详细地址"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="time"
        label="营业时间"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="phone"
        label="电话"
        width="120"
      ></el-table-column>
      <!-- <el-table-column align="center" sortable prop="description" label="收费说明" width="120"></el-table-column> -->
      <el-table-column
        align="center"
        sortable
        prop="createTime"
        label="创建时间"
        width="150"
      >
        <template slot-scope="scope">
          <div>{{ transformDate(scope.row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openSite(scope.row)"
            >查看详情</el-button
          >
          <el-button size="mini" type="primary" @click="upAdminSite(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" @click="deleSite(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情 -->
    <el-dialog title="站点详情页：" :visible.sync="editFormDetails" width="50%">
      <el-form label-width="100px">
        <el-form-item label="站点名称：">
          <span v-html="this.Details.name"></span>
        </el-form-item>
        <el-form-item label="站点图片：">
          <ul
            style="display: flex; flex-wrap: wrap;overflow: auto; width: 100%;height: 160px;padding:0;margin:0;"
          >
            <li
              v-for="url in urlArr"
              :key="url"
              style="width: 140px;height: 140px;margin:3px 0 3px 14px"
            >
              <el-image
                v-if="url"
                style="width: 140px;height: 140px;"
                :src="url"
                :preview-src-list="[url]"
              ></el-image>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="纬度：">
          <span v-html="this.Details.latitude"></span>
        </el-form-item>
        <el-form-item label="经度：">
          <span v-html="this.Details.longitude"></span>
        </el-form-item>
        <el-form-item label="停车费：">
          <span v-html="this.Details.parkCost"></span>
        </el-form-item>
        <el-form-item label="详细地址：">
          <span v-html="this.Details.detail"></span>
        </el-form-item>
        <el-form-item label="营业时间：">
          <span v-html="this.Details.time"></span>
        </el-form-item>
        <el-form-item label="站点状态：">
          <span v-if="this.Details.status == 0">开放</span>
          <span v-if="this.Details.status == 1">休息</span>
          <span v-if="this.Details.status == 2">故障</span>
          <span v-if="this.Details.status == 3">认领</span>
        </el-form-item>
        <el-form-item label="电话：">
          <span v-html="this.Details.phone"></span>
        </el-form-item>
        <el-form-item label="收费说明：">
          <span v-html="this.Details.description"></span>
        </el-form-item>
        <el-form-item label="创建时间：" prop="createTime">
          {{ transformDate(this.Details.createTime) }}
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑界面 -->
    <el-dialog :title="tit" :visible.sync="editFormVisiible" width="50%">
      <el-form label-width="100px">
        <el-form-item label="站点名">
          <el-input
            size="small"
            v-model="xiugai.name"
            auto-complete="off"
            placeholder="请输入站点名"
          ></el-input>
        </el-form-item>
        <el-form-item label="站点图片">
          <div style="display: flex;">
            <el-upload
              action=""
              :http-request="mainImgUpload"
              :show-file-list="false"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <ul style="" class="urlLun">
              <li
                v-for="(url, index) in urlArr"
                :key="url"
                style="width: 140px;height: 140px;margin:3px 0 3px 14px;  position:relative"
              >
                <el-image
                  :src="url"
                  style="width: 140px;height: 140px;"
                  :preview-src-list="[url]"
                />
                <el-button
                  class="deleUrl"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="DeleUrl(index)"
                ></el-button>
              </li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input
            size="small"
            v-model="xiugai.latitude"
            auto-complete="off"
            placeholder="请输入纬度"
          ></el-input>
        </el-form-item>
        <el-form-item label="经度">
          <el-input
            size="small"
            v-model="xiugai.longitude"
            auto-complete="off"
            placeholder="请输入经度"
          ></el-input>
        </el-form-item>
        <el-form-item label="停车费">
          <el-input
            size="small"
            v-model="xiugai.parkCost"
            auto-complete="off"
            placeholder="请输入停车费"
          ></el-input>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input
            size="small"
            v-model="xiugai.detail"
            auto-complete="off"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="营业时间">
          <el-input
            size="small"
            v-model="xiugai.time"
            auto-complete="off"
            placeholder="请输入营业时间"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input
            size="small"
            v-model="xiugai.phone"
            auto-complete="off"
            placeholder="请输入电话"
          ></el-input>
        </el-form-item>

        <el-form-item label="站点状态">
          <el-select
            v-model="xiugai.status"
            placeholder="请选择站点状态"
            size="small"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收费说明">
          <quill-editor
            v-model="xiugai.description"
            :options="editorOption"
            style="height: 300px;"
            ref="QuillEditor"
          >
          </quill-editor>
        </el-form-item>
        <div style="height:90px"></div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="addSites()"
          v-if="tit == '添加'"
          >添加</el-button
        >
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="upAdminSites()"
          v-if="tit == '修改'"
          >修改</el-button
        >
      </div>
    </el-dialog>
    <!-- 富文本图片 -->
    <el-dialog title="选择图片" :visible.sync="uploadVisible" width="190px">
      <div>
        <div class="upload-demo">
          <el-upload
            action=""
            :http-request="mainImgUpload3"
            :show-file-list="false"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </div>
    </el-dialog>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import {
  getAdminSiteList,
  getAdminSiteInfo,
  addAdminSite,
  deAdminSite,
  upAdminSite
} from "../../api/userMG";
import client from "@/utils/ossClient.js";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image", "video"], // 对于图片上传这是重点
  ["clean"] // remove formatting button
];
export default {
  data() {
    return {
      siteData: [],
      loading: false,
      name: "",
      userId: -1,
      status: "",
      detail: "",
      phone: "",
      userType: "",
      tit: "添加",
      options: [
        {
          value: 0,
          label: "开放"
        },
        {
          value: 1,
          label: "休息"
        },
        {
          value: 2,
          label: "故障"
        },
        {
          value: 3,
          label: "认领"
        }
      ],
      options1: [
        {
          value: 0,
          label: "普通合伙人"
        },
        {
          value: 1,
          label: "平台合伙人"
        }
      ],
      editFormDetails: false,
      Details: [],
      urlArr: [],
      editFormVisiible: false,
      uploadVisible: false,
      xiugai: {
        id: "",
        name: "",
        latitude: "",
        longitude: "",
        parkCost: "",
        detail: "",
        time: "",
        phone: "",
        description: "",
        createTime: "",
        status: "",
        urls: ""
      },
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 10
      },
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: value => {
                if (value) {
                  // 在这里编写图片按钮点击操作
                  this.uploadVisible = true;
                  this.cursorIndex = this.$refs.QuillEditor.quill.getSelection().index;
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        }
      }
    };
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    this.getdata(1);
  },
  methods: {
    // 分页插件事件
    callFather(parm) {
      this.pageparm.page = parm.currentPage;
      this.getdata(parm.currentPage);
    },
    mainImgUpload3(file) {
      var self = this;
      //判断扩展名
      const tmpcnt = file.file.name.lastIndexOf(".");
      const exname = file.file.name.substring(tmpcnt + 1);
      const names = ["jpg", "jpeg", "webp", "png", "bmp"];
      // if (names.indexOf(exname) < 0) {
      //   this.$message.error("不支持的格式!");
      //   return;
      // }
      const fileName = file.file.uid + "." + exname;
      client
        .put(fileName, file.file)
        .then(res => {
          if (res.url) {
            console.log("res.url=======", res.url);
            self.getUrl(res.url);
          } else {
            this.$message.error("文件上传失败");
          }
        })
        .catch(err => {});
    },
    getUrl(url) {
      this.uploadVisible = false;
      // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill;
      // 如果上传成功
      if (url) {
        // 插入图片，res为服务器返回的图片链接地址

        quill.insertEmbed(this.cursorIndex, "image", url);
        // 调整光标到最后
        quill.setSelection(this.cursorIndex + 1);
      } else {
        // 提示上传失败信息
      }
    },
    exportExcel() {
      var parameter = {
        page: -2,
        name: this.name,
        userId: this.userId,
        status: this.status,
        detail: this.detail,
        phone: this.phone,
        userType: this.userType
      };
      getAdminSiteList(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.siteData = res.data.list;
          return;
        }
      });
      setTimeout(() => {
        //转换成excel时，使用原始的格式
        var xlsxParam = { raw: true };
        let fix = document.querySelector(".el-table__fixed-right");
        let wb;
        //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
        if (fix) {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el.removeChild(fix),
            xlsxParam
          );
          this.$refs.multipleTable.$el.appendChild(fix);
        } else {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el,
            xlsxParam
          );
        }
        var wbout = XLSX.write(wb, {
          bookType: "xls",
          bookSST: true,
          type: "array"
        });
        try {
          // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(
              new Blob([wbout], { type: "application/octet-stream" }),
              "管理员站点列表.xlsx"
            );
          } else {
            // 在其他浏览器中使用file-saver保存文件
            saveAs(
              new Blob([wbout], { type: "application/octet-stream" }),
              "管理员站点列表.xlsx"
            );
          }
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      }, 1000);
      setTimeout(() => {
        this.getdata(1);
      }, 2000);
    },
    // 删除图片
    DeleUrl(index) {
      this.urlArr;
      this.urlArr.splice(index, 1);
    },
    // 修改
    upAdminSites() {
      this.loading = true;
      this.xiugai.urls = this.urlArr;
      upAdminSite(this.xiugai).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisiible = false;
          this.$message.success(res.msg);
          this.getdata(this.pageparm.currentPage);
        } else {
          this.editFormVisiible = false;
          this.$message.error(res.msg);
        }
      });
    },
    // 添加
    addSites() {
      (this.loading = true), (this.xiugai.urls = this.urlArr);
      addAdminSite(this.xiugai).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisiible = false;
          this.$message.success(res.msg);
          this.getdata(1);
        } else {
          this.editFormVisiible = false;
          this.$message.error(res.msg);
        }
      });
    },
    // 打开编辑器
    upAdminSite(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            this.editFormVisiible = true;
            if (row != undefined && row != "undefined") {
              console.log(row);
              this.tit = "修改";
              this.xiugai.id = row.id;
              this.xiugai.name = row.name;
              this.xiugai.latitude = row.latitude;
              this.xiugai.longitude = row.longitude;
              this.xiugai.parkCost = row.parkCost;
              this.xiugai.detail = row.detail;
              this.xiugai.phone = row.phone;
              this.xiugai.time = row.time;
              this.xiugai.status = row.status;
              this.xiugai.description = row.description;
              this.xiugai.createTime = row.createTime;
              this.urlArr = row.urls.split(",");
            } else {
              this.tit = "添加";
              this.xiugai.id = "";
              this.xiugai.name = "";
              this.xiugai.latitude = "";
              this.xiugai.longitude = "";
              this.xiugai.parkCost = "";
              this.xiugai.detail = "";
              this.xiugai.phone = "";
              this.xiugai.time = "";
              this.xiugai.status = "";
              this.xiugai.description = "";
              this.xiugai.createTime = "";
              this.urlArr = [];
            }
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 关闭编辑对话框
    closeDialog() {
      this.editFormVisiible = false;
      this.$message({
        type: "info",
        message: "已取消编辑"
      });
    },
    // 删除
    deleSite(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            this.$confirm("确定删除吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "error"
            })
              .then(() => {
                let data = {
                  id: row.id
                };
                deAdminSite(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.getdata(this.pageparm.currentPage);
                  } else {
                    this.$message.error(res.msg);
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除"
                });
              });
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 自定义上传方法
    mainImgUpload(file) {
      // 判断扩展名
      const tmpcnt = file.file.name.lastIndexOf(".");
      const exname = file.file.name.substring(tmpcnt + 1);
      const names = ["jpg", "jpeg", "webp", "png", "bmp"];
      if (names.indexOf(exname) < 0) {
        this.$message.error("不支持的格式!");
        return;
      }
      const fileName = file.file.uid + "." + exname;
      client
        .put(fileName, file.file)
        .then(res => {
          if (res.url) {
            this.urlArr.push(res.url);
          } else {
            this.$message.error("文件上传失败");
          }
        })
        .catch(err => {});
    },
    // 打开详情页面
    openSite(row) {
      this.loading = true;
      this.editFormDetails = true;
      let data = {
        id: row.id
      };
      getAdminSiteInfo(data).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.Details = res.data.data;
          this.urlArr = this.Details.urls.split(",");
          return;
        }
      });
    },
    // 是否合伙人
    UserType: function(row) {
      if (row.userType == 0) {
        return "普通合伙人";
      } else if (row.userType == 1) {
        return "平台合伙人";
      }
    },
    // 站点状态
    Status: function(row) {
      if (row.status == 0) {
        return "开放";
      } else if (row.status == 1) {
        return "休息";
      } else if (row.status == 2) {
        return "故障";
      } else if (row.status == 3) {
        return "认领";
      }
    },
    // 搜索数据
    search() {
      this.getdata(1);
    },
    // 重置数据
    chongzhi() {
      this.name = "";
      this.userId = -1;
      this.status = "";
      this.detail = "";
      this.phone = "";
      this.userType = "";
      this.getdata(1);
    },
    // 获取数据
    getdata(page) {
      this.loading = true;
      var parameter = {
        page: (page - 1) * 20,
        name: this.name,
        userId: this.userId,
        status: this.status,
        detail: this.detail,
        phone: this.phone,
        userType: this.userType
      };
      getAdminSiteList(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.siteData = res.data.list;
          this.pageparm.currentPage = page;
          this.pageparm.total = res.data.count;
          return;
        }
      });
    }
  }
};
</script>

<style>
li {
  list-style: none;
}

.urlLun {
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  width: 100%;
  height: 160px;
  padding: 0;
  margin: 0;
}

.deleUrl {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
}

.urlLun li:hover .deleUrl {
  display: block;
}
</style>
